<?php
class AdviserForm extends UserForm {

	public $first_name;
	public $last_name;
	public $phone_number;
	public $initials;
	private $adviser = null;

	public function __construct() {
		$this->user_type = Constants::ADVISER_USER_TYPE;
	}

	public function rules() {
		return array_merge(parent::rules(), array (
			array (
				'first_name, initials',
				'required',
				'on' => self::CREATE.','.self::UPDATE
			),
			array (
				'first_name, last_name, phone_number, initials',
				'changeAdviser',
				'on' => self::CREATE.','.self::UPDATE
			),
			array (
				'first_name, last_name, phone_number, initials',
				'save'
			)
		));
	}

	public function attributeLabels() {
		return array_merge(parent::attributeLabels(), array (
			'first_name' => Yii::t('user', 'First Name'),
			'last_name' => Yii::t('user', 'Last Name'),
			'phone_number' => Yii::t('user', 'Phone Number'),
			'initials' => Yii::t('user', 'Initials')
		));
	}

	public function changeAdviser($attribute, $params) {
		$adviser = $this->getAdviser();
		if (!$this->hasErrors()) {
			$adviser->first_name = $this->first_name;
			$adviser->last_name = $this->last_name;
			$adviser->phone_number = $this->phone_number;
			$adviser->initials = $this->initials;
		}
	}

	protected function getAdviser() {
		if ($this->adviser == null) {
			if ($this->getUser() != null && !$this->hasErrors()) {
				$this->adviser = $this->getUser()->adviser;

				if ($this->adviser == null && !$this->scenario == self::CREATE) {
					$this->addError(Yii::t('user', 'User {username} is not an adviser', array('{username}', $this->username)));
				}

				if ($this->adviser == null && $this->scenario == self::CREATE) {
					$this->adviser = new Adviser();
					$this->adviser->username = $this->username;
					$this->user->adviser = $this->adviser;
				}
			}
		}

		return $this->adviser;
	}

	public function save($attribute, $params) {
		parent::save($attribute, $params);
		if (!$this->hasErrors()){
			$adviser = $this->getAdviser();
			$adviser->save();
		}
	}
}
?>
